<template>
  <CDialog
    :title="title"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    size="small"
    @cancel="handleClose"
    @confirm="handleConfirm"
    confirm-text="保存"
  >
    <div class="g-mb20 low-carbon-material-dialog-container" v-loading="loading">
      <el-form ref="formRef" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="材料名称：" prop="materialName">
          <el-input v-model="formData.materialName" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="关联因子：" prop="factorNo">
          {{ factorInfo }}
          <el-button text type="primary" @click="handleChangeFactor" :loading="loading">{{
            factorOpBtnText
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <CFootprintFactorDrawer
      v-model:visible="factorDialogVisible"
      @finish="handleFinish"
    ></CFootprintFactorDrawer>
  </CDialog>
</template>
<script lang="ts" setup name="AddOrEditLowCarbonMaterial">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { rules } from './rules';
import { useMessage } from '@/hooks/useMessage';
import CFootprintFactorDrawer from '@/businessComponents/CFootprintFactorDrawer/index.vue';
import type { GetLowCarbonMaterialListResult } from '@/apis/system/config/model/lowCarbonMaterialModel';
import { postCreateLowCarbonMaterial } from '@/apis/system/config/lowCarbonMaterial';

interface CSetEmissionFactorDialogProps {
  visible: boolean;
  loading?: boolean;
  materialInfo?: GetLowCarbonMaterialListResult;
}
const props = withDefaults(defineProps<CSetEmissionFactorDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => props.visible,
  val => {
    if (val) {
      init();
    }
  }
);

const title = computed(() => {
  return props.materialInfo ? '编辑低碳材料' : '新建低碳材料';
});

const factorInfo = computed(() => {
  if (formData.emissionFactor || typeof formData.emissionFactor === 'number') {
    return formData.emissionFactor + formData.factorUnit;
  }
  return '';
});

const factorOpBtnText = computed(() => {
  return props.materialInfo ? '更换因子' : '关联因子';
});

const formRef = ref();
const loading = ref(false);
const formData = reactive({
  materialName: '',
  emissionFactor: '',
  factorUnit: '',
  factorNo: ''
});

async function init() {
  if (props.materialInfo) {
    formData.materialName = props.materialInfo.materialName;
    formData.emissionFactor = props.materialInfo.emissionFactor;
    formData.factorUnit = props.materialInfo.factorUnit;
    formData.factorNo = props.materialInfo.factorNo;
  } else {
    formData.materialName = '';
    formData.emissionFactor = '';
    formData.factorUnit = '';
    formData.factorNo = '';
  }
}

const factorDialogVisible = ref(false);

/**
 * 更换因子
 */
function handleChangeFactor() {
  console.log('handleChangeFactor');
  factorDialogVisible.value = true;
}

async function handleFinish(row: any) {
  console.log('handleFinish', row);
  formData.emissionFactor = row.emissionFactor;
  formData.factorUnit = row.factorUnit;
  formData.factorNo = row.factorNo;
}

function handleConfirm() {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      try {
        const params = {
          materialName: formData.materialName,
          factorNo: formData.factorNo
        };
        if (props.materialInfo) {
          Object.assign(params, {
            relationNo: props.materialInfo.relationNo
          });
        }
        loading.value = true;
        await postCreateLowCarbonMaterial(params);
        createMessage.success('保存成功！');
        loading.value = false;
        emits('refresh');
        handleClose();
      } catch (error) {
        loading.value = false;
        console.log('error', error);
      }
    }
  });
}

function handleClose() {
  dialogVisible.value = false;
}
</script>
<style lang="scss" scoped>
.low-carbon-material-dialog-container {
  :deep(.el-form--inline .el-form-item) {
    width: 100%;
  }
}
</style>
